﻿namespace RialternativeSample.ViewModels
{
    using System.ComponentModel.DataAnnotations;
    using System.ServiceModel.DomainServices.Client.ApplicationServices;
    using System.Windows.Input;
    using RialternativeSample.Client.Commanding;
    using RialternativeSample.Client.Models;
    using RialternativeSample.Services.Interfaces;
    using RialternativeSample.ViewModels.Interfaces;

    public class LoginViewModel : ILoginViewModel
    {
        private IDialogService dialogService;

        public LoginViewModel(IDialogService dialogService)
        {
            this.dialogService = dialogService;
            this.LoginInfo = new LoginInfo();
            this.LoginCommand = new RelayCommand<object>(o => this.Login());
            this.CancelLoginCommand = new RelayCommand<object>(o => this.CancelLogin());
        }

        public ICommand LoginCommand { get; private set; }

        public ICommand CancelLoginCommand { get; private set; }

        public LoginInfo LoginInfo { get; private set; }

        private void CancelLogin()
        {
            if (this.LoginInfo.CurrentLoginOperation != null && this.LoginInfo.CurrentLoginOperation.CanCancel)
            {
                this.LoginInfo.CurrentLoginOperation.Cancel();
            }
            else
            {
                this.dialogService.CloseDialog(this);
            }
        }

        private void Login()
        {
            this.LoginInfo.CurrentLoginOperation =
                WebContext.Current.Authentication.Login(this.LoginInfo.ToLoginParameters(), this.OnLoginOperationCompleted, null);
        }

        private void OnLoginOperationCompleted(LoginOperation loginOperation)
        {
            if (loginOperation.LoginSuccess)
            {
                this.dialogService.CloseDialog(this);
            }
            else if (loginOperation.HasError)
            {
                // TODO : Manage error handling
                //loginOperation.MarkErrorAsHandled();
            }
            else if (!loginOperation.IsCanceled)
            {
                this.LoginInfo.ValidationErrors.Add(new ValidationResult("Bad username or password", new string[] { "UserName", "Password" }));
            }
        }
    }
}
